package br.org.imazon.sad;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.servlet.http.HttpSession;

public class Authenticate {
	
    
    private Authenticate() {}
    
    public static String auth(HttpSession session, String service) {
    	String result = null;
 
    	PersistenceManager pm = PMF.get().getPersistenceManager();

    	
    	String query = "select from " + AuthModel.class.getName() + " where service == '" + service + "'";
    	@SuppressWarnings("unchecked")
    	List<AuthModel> models = (List<AuthModel>) pm.newQuery(query).execute();
    	String attName = "auth";
    	String emailName = "email";
    	
    	if (models.size() > 0) {
    		for (AuthModel model: models) {
    			session.setAttribute(attName + model.getService(), model.getAuthKey());
    			session.setAttribute(emailName + model.getService(), model.getEmail());
    			result = model.getAuthKey();
    		}
    	  
    	} else {
    		System.out.println("found no models");
    	}
    	return result;
    }
	
}
